package com.it.labservice.controller;

import com.it.labservice.entity.User;
import com.it.labservice.repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AuthController {
    
    @Autowired
    private UserRepository userRepository;
    
    @GetMapping("/login")
    public String showLoginPage() {
        return "login";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam String username, 
                       @RequestParam String password, 
                       HttpSession session, 
                       Model model) {
        
        System.out.println("登录尝试 - 用户名: " + username + ", 密码: " + password);
        
        // 查找用户
        User user = userRepository.findByUsername(username);
        
        if (user != null) {
            System.out.println("找到用户: " + user.getName() + ", 数据库密码: " + user.getPassword() + ", 激活状态: " + user.getIsActive());
        } else {
            System.out.println("用户不存在: " + username);
        }
        
        // 简单的密码验证（实际项目中应该使用加密）
        if (user != null && password.equals(user.getPassword()) && user.getIsActive()) {
            // 登录成功，将用户信息存入session
            System.out.println("登录成功: " + user.getName());
            session.setAttribute("currentUser", user);
            
            // 根据用户角色跳转到不同页面
            if (User.UserRole.ADMIN.equals(user.getRole())) {
                return "redirect:/dashboard?loginSuccess=true";  // 超级管理员跳转到仪表盘
            } else {
                return "redirect:/?loginSuccess=true";  // 实验室管理员跳转到安全检查系统
            }
        } else {
            // 登录失败
            System.out.println("登录失败 - 密码匹配: " + (user != null && password.equals(user.getPassword())) + 
                             ", 用户激活: " + (user != null && user.getIsActive()));
            return "redirect:/login?error=true";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login?logout=true";
    }
} 